<template>
  <div class="vehicle-management">
    <div id="map-container" class="map-container" :style="{ width: isCollapsed ? '100%' : '75%' }">
      <div id="mapDiv" />

      <el-tooltip
        effect="dark"
        content="找不到我在哪？点一下就找到"
        placement="left"
      >
        <div
          class="position-icon"
          @click="handleBackOrigin"
        >
          <svg-icon
            icon-class="position"
            class-name="position-icon__icon"
          />
        </div>
      </el-tooltip>
    </div>
    <div v-show="!isCollapsed" class="vehicle-list">
      <div class="title">
        <h3>车辆信息</h3>
      </div>
      <div class="vehicle-list-content">
        <div
          v-for="(vehicle, index) in vehicles"
          :key="index"
          @click="getCurrentVehicleLocation(vehicle.id)"
        >
          <el-card
            style="max-width: 100%;margin-bottom: 10px;cursor: pointer;"
            :shadow="vehicle.id === id ? 'always' : 'hover'"
            :class="{ 'active': vehicle.id === id }"
          >
            <template #header>
              <div class="card-header sw">
                <strong>{{ vehicle.license_plate_number }}</strong>
                <span>车辆状态：
                  <el-tag
                    v-if="vehicle.gps && vehicle.gps.status === 5"
                    type="primary"
                  >
                    {{ getStatus(vehicle.gps.status) }}
                    {{ getUpdateTime(vehicle.gps.statusUpdateTime) }}
                  </el-tag>

                  <el-tag
                    v-else
                    type="primary"
                  >
                    {{ getStatus(vehicle.gps ? vehicle.gps.status : null) }}
                  </el-tag>
                </span>
              </div>
            </template>
            <el-descriptions v-if="vehicle.gps" :column="2" border>
              <el-descriptions-item label="驾驶员">王炸</el-descriptions-item>
              <el-descriptions-item label="当前车辆速度">{{ vehicle.gps.speed }}KM/h</el-descriptions-item>
              <el-descriptions-item label="当前位置">{{ addresses[`${vehicle.gps.lat},${vehicle.gps.lon}`] || '加载中...' }}</el-descriptions-item>
              <el-descriptions-item label="最后定位时间">
                {{ vehicle.gps.gpsTime }}
              </el-descriptions-item>
              <el-descriptions-item label="GPS电量">
                <el-tag effect="dark" type="success">{{ vehicle.gps.electQuantity }}%</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="车辆类型">
                {{ vehicle.type ? vehicle.type.name : '未知' }}
              </el-descriptions-item>
            </el-descriptions>
            <div v-else style="padding: 10px; color: #909399; text-align: center;">
              暂无GPS数据
            </div>

            <div class="sw">
              <el-button type="text" @click.stop="historyGps(vehicle.id)">历史行车记录</el-button>
            </div>
          </el-card>
        </div>

      </div>
    </div>
    <div class="collapse-btn" @click="toggleCollapse">
      <i :class="isCollapsed ? 'el-icon-d-arrow-left' : 'el-icon-d-arrow-right'" />
    </div>
    <el-dialog :visible.sync="historyVisible" title="历史行车记录" width="50%">
      <el-form :inline="true" :model="formHistory" class="demo-form-inline">
        <el-form-item label="查询时间">
          <el-date-picker
            v-model="formHistory.time"
            type="daterange"
            :shortcuts="shortcuts"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
        </el-form-item>
        <el-form-item label="">
          <el-button type="primary" @click="queryHistory()">查询</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>

</template>

<script>
import {
  getVehiclesList
} from '@/api/vehicleService'
import { address, newLocation } from '@/api/gps'
import vehicleGpsMixin from '@/views/vehicleService/js/vehicleGpsMixin'
const T = window.T
export default {
  name: '',
  mixins: [vehicleGpsMixin],
  data() {
    return {
      map: null,
      isCollapsed: false,
      vehicles: [],
      lat: null,
      lng: null,
      addresses: {},
      id: null,
      car: {},
      marker: null,
      label: null,
      labels: null,
      rotatedCarDiv: null,
      historyVisible: false,
      formHistory: {
        time: null,
        id: null
      },
      shortcuts: [
        {
          text: 'Last week',
          value: () => {
            const end = new Date()
            const start = new Date()
            start.setDate(start.getDate() - 7)
            return [start, end]
          }
        },
        {
          text: 'Last month',
          value: () => {
            const end = new Date()
            const start = new Date()
            start.setMonth(start.getMonth() - 1)
            return [start, end]
          }
        },
        {
          text: 'Last 3 months',
          value: () => {
            const end = new Date()
            const start = new Date()
            start.setMonth(start.getMonth() - 3)
            return [start, end]
          }
        }]
    }
  },
  created() {
    this.id = this.$route.params.id ? Number(this.$route.params.id) : null
  },
  mounted() {
    this.initData()
  },
  methods: {
    toggleCollapse() {
      this.isCollapsed = !this.isCollapsed
      // 调整地图大小
      if (this.map) {
        setTimeout(() => {
          this.map.checkResize()
        }, 300)
      }
    },
    focusVehicle(vehicle) {
      // 聚焦到地图上的对应车辆
      console.log('聚焦车辆:', vehicle.plateNumber)
    },
    async initData() {
      this.map = new T.Map('mapDiv', {
        projection: 'EPSG:900913'
      })

      try {
        const res = await getVehiclesList({ 'gps': true })
        console.log('API Res:', res)

        // 1. 安全获取数组，防止为 null
        const carList = res.data.car || []
        const gpsList = res.data.gps || []

        // 2. 先 filter 过滤掉 null/undefined 项，再 map
        const map2 = new Map(
          gpsList
            .filter(item => item && item.imei) // 确保 item 存在且有 imei
            .map(item => [item.imei, item])
        )

        // 3. 合并时同样过滤无效 car 数据
        const merged = carList
          .filter(item => item) // 过滤掉空的车辆数据
          .map(item => {
            return {
              ...item,
              // 安全获取 gps，如果 item.imei 不存在则给空对象
              gps: (item.imei && map2.get(item.imei)) || {}
            }
          })

        console.log('Merged:', merged)

        // 为每个车辆获取地址
        for (const vehicle of merged) {
          if (vehicle.gps && vehicle.gps.lat && vehicle.gps.lon) {
            await this.getAddress(vehicle.gps.lat, vehicle.gps.lon)
          }
        }

        this.vehicles = merged

        // 处理选中车辆逻辑
        const targetId = this.id

        const result = this.vehicles.find(item => item.id === targetId)

        // 使用可选链或安全访问
        const lat = result?.gps?.lat
        const lng = result?.gps?.lon

        if (lat && lng) {
          console.log(lat, lng)
          var zoom = 18
          this.map.centerAndZoom(new T.LngLat(lng, lat), zoom)
          this.car = result
          await this.initCar()
        } else {
          if (result && !result.imei) {
            this.$message.error('该车辆暂未绑定GPS设备，请绑定后尝试')
          }
          // 如果 mixin 里有 defaultLonLat
          const defaultPos = this.defaultLonLat || [116.40769, 39.89945]
          this.setCenterAndZoom(defaultPos[0], defaultPos[1], 18)
        }

        const scale = new T.Control.Scale()
        const control = new T.Control.Zoom()

        this.map.addControl(control)
        this.map.addControl(scale)
      } catch (error) {
        console.error('Init Data Error:', error)
        this.$message.error('数据加载失败，请检查网络')
      }
    },
    createRotatedCarLabel(degree) {
      const container = document.createElement('div')
      container.className = 'rotated-car-icon'
      container.innerHTML = `
    <img src="https://obs-user-test.obs.cn-east-3.myhuaweicloud.com:443/pictures/test_1753672404_aImt0o3Jg7.png" />
  `
      container.style.transform = `rotate(${degree}deg)`
      return container
    },
    async initCar() {
      // 安全检查
      if (!this.car || !this.car.id) return false

      const res = await newLocation({ 'id': this.car.id })
      let lon, lat, degree

      if (!res.data || !res.data[0]) {
        this.$message.warning('车辆暂无实时位置信息，使用上次位置显示')
        // Fallback 到静态 gps 数据
        if (this.car.gps && this.car.gps.lat && this.car.gps.lon) {
          this.car.lastGps = {
            lastLon: this.car.gps.lon,
            lastLat: this.car.gps.lat,
            lastCourse: this.car.gps.course || 0,
            status: this.car.gps.status || 0,
            lastLocationTime: this.car.gps.gpsTime || '',
            lastDataTime: new Date().toISOString(),
            lastLocationInfoType: 0
          }
          lon = this.car.lastGps.lastLon
          lat = this.car.lastGps.lastLat
          degree = this.car.lastGps.lastCourse || 0
          this.addRotatedCarToMap(lon, lat, degree - 90)
          // 确保回退时居中
          this.setCenterAndZoom(lon, lat, 18)
          return true
        } else {
          this.$message.error('车辆暂无位置信息，请稍后重试或检查 GPS 绑定')
          return false
        }
      }

      // 成功获取实时数据
      console.log('res.data[0] --------->', res.data[0])
      this.car.lastGps = res.data[0]
      lon = this.car.lastGps.lastLon
      lat = this.car.lastGps.lastLat
      degree = this.car.lastGps.lastCourse || 0

      // 添加旋转图标
      this.addRotatedCarToMap(lon, lat, degree - 90)

      this.setCenterAndZoom(lon, lat, 18)

      // 地址信息弹窗
      const addressres = await address({ 'lat': lat, 'lon': lon })

      const label = new T.Label({
        text: `<b>车牌号： ${this.car.license_plate_number} </b><br/>
      <b>当前经纬度： ${lon},${lat} </b><br/>
      <b>车辆位置： ${addressres.data.formatted_address || '未知位置'} </b><br/>
      <b>车辆方向： ${this.getDirection(degree)} </b><br/>
      <b>定位类型： ${this.getLocationInfoType(this.car.lastGps.lastLocationInfoType)}定位</b><br/>
      <b>车辆状态： ${this.getStatus(this.car.lastGps.status)} </b><br/>
      <b>车辆最后定位时间： ${this.car.lastGps.lastLocationTime} </b><br/>
      <b>GPS最后更新时间： ${this.car.lastGps.lastDataTime} </b><br/>
      <span id="closeBtn" style="cursor: pointer;color:red">关闭</span>`,
        position: new T.LngLat(lon, lat),
        offset: new T.Point(0, -280)
      })

      this.label = label
      this.map.addOverLay(this.label)

      this.$nextTick(() => {
        setTimeout(() => {
          const closeBtn = document.getElementById(`closeBtn`)
          if (closeBtn) {
            closeBtn.addEventListener('click', this.removeLabel)
          }
        }, 0)
      })
      return true
    },
    addRotatedCarToMap(lon, lat, degree) {
      // 清理之前的 marker
      if (this.rotatedCarDiv) {
        const mapDiv = document.getElementById('mapDiv')
        if (mapDiv && mapDiv.contains(this.rotatedCarDiv)) {
          mapDiv.removeChild(this.rotatedCarDiv)
        }
      }
      // 1. 创建 DOM 图标
      const div = document.createElement('div')
      div.className = 'rotated-marker'
      div.innerHTML = `<img src="https://obs-user-test.obs.cn-east-3.myhuaweicloud.com:443/pictures/test_1753672404_aImt0o3Jg7.png" />`
      div.style.transform = `rotate(${degree}deg)`
      div.style.position = 'absolute'
      div.style.width = '41px'
      div.style.height = '22px'
      div.style.transformOrigin = 'center center'

      // 2. 插入地图容器
      const mapDiv = document.getElementById('mapDiv')
      if (!mapDiv) return
      mapDiv.appendChild(div)

      // 3. 更新位置函数
      const updatePosition = () => {
        const pixel = this.map.lngLatToContainerPoint(new T.LngLat(lon, lat))
        div.style.left = `${pixel.x - 20}px`
        div.style.top = `${pixel.y - 11}px`
      }

      updatePosition()

      // 4. 绑定地图事件
      this.map.addEventListener('move', updatePosition)
      this.map.addEventListener('zoomend', updatePosition)

      // 5. 可选：点击图标显示车辆信息标签
      div.addEventListener('click', () => {
        this.map.addOverLay(this.label)
      })

      // 6. 存引用以便清除
      this.rotatedCarDiv = div
    },
    async getAddress(lat, lon) {
      if (!lat || !lon) {
        return '未知位置'
      }
      const key = `${lat},${lon}`
      if (!this.addresses || !this.addresses[key]) {
        const res = await address({ 'lat': lat, 'lon': lon })
        // 防止 res.data 为空
        const addr = res.data ? (res.data.formatted_address || res.data) : '未知位置'
        this.$set(this.addresses || {}, key, addr)
      }
      return typeof this.addresses[key] === 'object'
        ? JSON.stringify(this.addresses[key])
        : this.addresses[key]
    },
    addLabel() {
      if (this.label) this.map.addOverLay(this.label)
    },
    removeLabel() {
      if (this.map && this.label) {
        try {
          this.map.removeOverLay(this.label)
        } catch (e) {
          console.warn('Label移除时出现轻微异常，已忽略', e)
        }
      }
      this.label = null
    },
    getUpdateTime(t) {
      if (!t) return ''
      const time = new Date(t.replace(/-/g, '/'))
      // 当前时间距离time差了多少时间，精确到天时分秒
      const now = new Date()
      const diff = now - time
      const days = Math.floor(diff / (1000 * 60 * 60 * 24))
      const hours = Math.floor(diff / (1000 * 60 * 60)) % 24
      const minutes = Math.floor(diff / (1000 * 60)) % 60
      const seconds = Math.floor(diff / 1000) % 60

      let result = ''
      if (days > 0) {
        result += `${days}天`
      }
      if (hours > 0 || days > 0) {
        result += `${hours}小时`
      }
      if (minutes > 0 || hours > 0 || days > 0) {
        result += `${minutes}分`
      }
      result += `${seconds}秒`

      return result
    },
    historyGps(id) {
      this.$router.push({
        path: '/vehicle-service/gps/history/' + id
      })
    },

    async getCurrentVehicleLocation(id) {
      // 1. 查找并更新 this.car 对象
      this.car = this.vehicles.find(item => item.id === id)

      if (!this.car || !this.car.imei) {
        return this.$message.error('该车辆暂未绑定GPS设备，请绑定后尝试')
      }

      // 2. 更新选中ID
      this.id = id
      this.removeLabel()

      if (this.rotatedCarDiv) {
        const mapDiv = document.getElementById('mapDiv')
        if (mapDiv && mapDiv.contains(this.rotatedCarDiv)) {
          this.map.removeEventListener('move', this.updatePosition)
          this.map.removeEventListener('zoomend', this.updatePosition)
          mapDiv.removeChild(this.rotatedCarDiv)
        }
        this.rotatedCarDiv = null
      }

      // 3. 初始化新车的标记和定位
      const initSuccess = await this.initCar()
      console.log('initSuccess', initSuccess)

      if (!initSuccess) {
        return
      }
    },

    setCenterAndZoom(lon, lat, zoom) {
      if (this.map) {
        this.map.centerAndZoom(new T.LngLat(lon, lat), zoom)
      }
    },

    handleBackOrigin() {
      if (!this.car.lastGps || !this.car.lastGps.lastLon || !this.car.lastGps.lastLat) {
        this.$message.warning('车辆位置信息不可用')
        return
      }
      const lon = this.car.lastGps.lastLon
      const lat = this.car.lastGps.lastLat

      this.setCenterAndZoom(lon, lat, 18)
    }

  }
}
</script>

<style scoped lang='scss'>
.vehicle-management {
  display: flex;
  height: 90vh;
  position: relative;
  // background: red;
}

.map-container {
  transition: all 0.5s cubic-bezier(0.25, 0.8, 0.25, 1);
  will-change: width;
  position: relative;

  .position-icon {
    width: 60px;
    height: 60px;
    border-radius: 10px;
    position: absolute;
    right: 20px;
    bottom: 30px;
    z-index: 9999;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #fff;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    &__icon {
      width: 30px;
      height: 30px;
    }
  }
}

#mapDiv {
  width: 100%;
  height: 100%;
  transition: all 0.5s ease;
}

.vehicle-list {
  position: absolute;
  right: 0;
  top: 0;
  background-color: #fff;
  width: 25%;
  z-index: 999;
  overflow: hidden;
  transition: all 0.5s cubic-bezier(0.25, 0.8, 0.25, 1);
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  border-radius: 15px 0 0 15px;
  height: 100%;
  padding-bottom: 80px;
}

.title {
  padding: 0 10px;
  display: flex;
  justify-content: space-between;
  text-align: center;
  border-bottom: 1px solid #eee;
}

.vehicle-list-content {
  max-height: 100%;
  overflow-y: auto;
  padding: 0 10px;
}

.vehicle-item {
  padding: 0 10px;
  border-bottom: 1px solid #eee;
  cursor: pointer;

  &:hover {
    background-color: #f5f7fa;
  }
}

.collapse-btn {
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 20px;
  height: 60px;
  background: #409EFF;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  border-radius: 4px 0 0 4px;
  z-index: 999;

  &:hover {
    background: #66b1ff;
  }
}

.sw {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.active {
  border: 1px solid #409EFF;
}

::v-deep .rotated-marker {
  z-index: 999;
  pointer-events: auto;
}

::v-deep .rotated-marker img {
  width: 100%;
  height: 100%;
  display: block;
}
</style>
